import axios from 'axios'
import { ElMessageBox, type Action } from 'element-plus'

export const request = axios.create({
  timeout: 10000,
  baseURL: 'http://localhost:8080/'
})

// 请求拦截器
request.interceptors.request.use(
  (config) => {
    // console.log('请求拦截器config:', config)
    return config
  },
  (error) => {
    // console.log('请求拦截器error:', error)
    return Promise.reject(error)
  }
)

// 响应拦截器
request.interceptors.response.use(
  (response) => {
    // 可以在这里对响应数据进行处理
    return response.data
  },
  (error) => {
    console.log('response error:', error)
    if (error.response && error.response.status === 403) {
      ElMessageBox.alert('登录信息已失效', '错误', {
        // if you want to disable its autofocus
        // autofocus: false,
        confirmButtonText: '返回登录',
        callback: (action: Action) => {
          if (action === 'confirm') {
            //清楚本地localstorg
            localStorage.removeItem('accessToken')
            localStorage.removeItem('refreshToken')
            // 处理未授权错误
            window.location.href = '/login'
          }
        }
      })
    } else if (error.code === 'ECONNABORTED') {
      // 连接超时或中断
      console.error('报错了：连接超时', error.message)
      return Promise.reject({
        code: '500',
        messsage: '连接超时',
        detail: error.message
      })
    } else {
      // 显示通用错误提示
      console.error('An error occurred:', error.message)
    }
    return Promise.reject(error)
  }
)
